﻿using System.Collections.Generic;
using System.Web.UI;
using System;

namespace PropertyExpression.TypedDataBinding.Web
{
    public abstract class GroupBinderBase<TData> : BinderBase, IGroupBinder<TData>
    {
        public GenericBinder<TControl, TData> Add<TControl>(object control) where TControl : Control
        {
            return this.Add((TControl)control);
        }

        public TData Data
        {
            get
            {
                return DataFunc();
            }
        }

        public Func<TData> DataFunc { get; set; }

        public virtual void ToModel()
        {
            Do(pair => pair.Value.ToModel(pair.Key));
        }

        public virtual void FromModel()
        {
            Do(pair => pair.Value.FromModel(pair.Key));
        }

        private void Do(Action<KeyValuePair<Control, IControlBinder>> doer)
        {
            foreach (var pair in GetCurrentDictionary())
            {
                doer(pair);
            }
        }

        protected abstract IEnumerable<KeyValuePair<Control, IControlBinder>> GetCurrentDictionary();

        public void Add<TControl>(TControl control, IControlBinder<TControl> controlBinder) where TControl : Control
        {
            AddToCashe(control, new ControlBinderWrapper<TControl>(controlBinder));
        }

        protected abstract void AddToCashe(Control control, IControlBinder controlBinder);

        //QDO: убрать отсюда
        public Control ParentControl { internal get; set; }
    }
}
